#include <stdio.h>
#include <stdlib.h>
#include <conio.h> 
#include <windows.h>

void gotoxy(int x,int y)		//光标移动到（x，y）的位置 
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle,pos); 
} 

void HideCursor()				//隐藏光标 
{
	CONSOLE_CURSOR_INFO cursor_info={1,0};
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}

int ball_x,ball_y;				//小球的位置，x竖着，y横着 
int ball_vx,ball_vy;			//小球速度 
int board_x,board_y;			//木板位置 
int high,width;					//背景大小 
int score;						//反弹小球次数 

void startup()					//数据初始化
{
	high=25;					//高 
	width=30;					//宽 
	
	ball_x=0;
	ball_y=width/2;
	
	ball_vx=ball_vy=1;
	
	board_y=width/2;
	board_x=high-2;
	
	score=0;
	
	HideCursor();
} 
void show()						//显示界面 
{
	int i,j;
	
	gotoxy(0,0);				//光标移动到原点位置，以下重新清屏 
	for(i=0;i<=high;i++)
	{
		for(j=0;j<=width;j++)
		{
			if((i == ball_x) && (j == ball_y))
			printf("o");		//输出小球 
			else if(i == high-1)//输出下边框 
			printf("-");
			else if(j == width)	//输出右边框 
			printf("|");
			else if((board_x == i) && (board_y == j))//输出木板 
			printf("******");
			else
			printf(" ");
		}
		printf("\n"); 
	}
	printf("反弹次数:%d\n",score);
}

void updatewith()				//与用户输出有关 
{
	char input;					//控制移动 
	
	if (kbhit())
	{
		input = getch();
		if(input == 'a')		//向左移动 
		board_y--; 
		if(input == 'd')		//向右移动 
		board_y++;
	}
}

void updatewithout()			//与用户输出无关 
{
	Sleep(80);
	ball_x += ball_vx;			//控制小球移动 
	ball_y += ball_vy;
	
	if(ball_x == board_x-1)
	{
		if((ball_y>=board_y) && (ball_y<=board_y+5))
		{
			ball_vx = -ball_vx;
			score++;
		}
	}

	else if(ball_x==board_x)
	{
		puts("'Game Over'");
		exit(0); 
	}
	
	if(ball_x == 0)//控制小球反弹 
	ball_vx = -ball_vx;
	if((ball_y ==width-1) || (ball_y == 0))
	ball_vy = -ball_vy;
}
 
int main() 
{
	startup();					//数据初始化
	while(1)					//游戏循环执行 
	{
		show();					//显示界面 
		updatewith();			//与用户输出有关 
		updatewithout();		//与用户输出无关 
	} 
	return 0;
}